from PyQt5.Qt import *
import sys
import cv2
from PyQt5 import QtGui


class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("视频")
        self.resize(1200,800)
        self.init()

    def init(self):
        self.initCanvas()
        self.opevCap()
        self.timer_id = self.startTimer(60)

    def initCanvas(self):
        self.lb = QLabel(self)
    def updateCanvas(self,img):
        w,h=img.shape[:2]
        print(w,h)
        self.lb.resize(h,w)
        image_show = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
        image_show = cv2.flip(image_show,1)
        showImage = QtGui.QImage(image_show.data,h,w,QImage.Format_RGB888)
        showImage = QPixmap.fromImage(showImage)
        # showImage = showImage.scaled(100 * 2,100 * 2, Qt.KeepAspectRatio); #// 将图片宽高扩大两倍，且在矩形内保持
        self.lb.setPixmap(showImage)

    def opevCap(self):
        cap = cv2.VideoCapture(0)
        self.cap = cap;
    def getImageFromCap(self):
        flag,frame = self.cap.read()
        return frame

    def timerEvent(self, evt):
        img = self.getImageFromCap()
        self.updateCanvas(img)

    def closeEvent(self, evt):
        self.killTimer(self.timer_id)
        self.cap.release()




if __name__=='__main__':
    app = QApplication(sys.argv)
    w = Window()
    w.show()
    sys.exit(app.exec_())